package cn.itsub.proxy.server.work.metrics.handler;

import java.net.InetSocketAddress;

import cn.itsub.proxy.server.work.metrics.MetricsCollector;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class BytesMetricsHandler extends ChannelDuplexHandler {

    //保存流量数据
    private long timestamp = 0;
    public void saveFlowData(MetricsCollector mc) {
        log.debug("saveFlowData");


    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
        MetricsCollector metricsCollector = MetricsCollector.getCollector(sa.getPort());
        long bytes = ((ByteBuf) msg).readableBytes();
        metricsCollector.incrementReadBytes(bytes);
        metricsCollector.incrementReadMsgs(1);
        metricsCollector._flow+=bytes;
        ctx.fireChannelRead(msg);
        saveFlowData(metricsCollector);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
        MetricsCollector metricsCollector = MetricsCollector.getCollector(sa.getPort());
        long bytes = ((ByteBuf) msg).readableBytes();
        metricsCollector.incrementWroteBytes(bytes);
        metricsCollector.incrementWroteMsgs(1);
        synchronized ("mcu"+metricsCollector.userId) {
            metricsCollector._flow+=bytes;
        }
        super.write(ctx, msg, promise);
        saveFlowData(metricsCollector);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
        MetricsCollector mc = MetricsCollector.getCollector(sa.getPort());
        int num = mc.getChannels().incrementAndGet();
        super.channelActive(ctx);

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress sa = (InetSocketAddress) ctx.channel().localAddress();
        MetricsCollector.getCollector(sa.getPort()).getChannels().decrementAndGet();
        super.channelInactive(ctx);
    }


}